"""
Case Type   : ustore copy from/to
Case Name   : ustore-copy-stdin/stdout
Create At   : 2024-07-25
Owner       : songjing20
Description :
    1.创建ustore表并插入数据
    2.执行copy from stdin
    3.执行copy to 标准输出stdout
    4.清理环境
Expect      :
    1.执行成功
    2.执行成功
    3.执行成功
    4.成功
    5.成功
History     :
"""
import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class UstoreCopy(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.node_pri = Node('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_copy_0009'

    def test_copy_from_to(self):
        text = '-----step1:创建ustore表并插入数据;expect:成功-----'
        self.log.info(text)
        sql = f'''drop table if exists {self.tb_name} cascade;
        create table {self.tb_name}(
        id int, age int, name char(10), fav text) with(storage_type=ustore);
        insert into {self.tb_name} values(1, 2, 'ss', 'dfd');'''
        sql_res = self.pri_sh.execut_db_sql(sql)
        self.log.info(sql_res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS,sql_res, f'执行失败:{text}')

        text = '-----step2:执行copy from stdin;expect:成功-----'
        self.log.info(text)
        copy_cmd = f'''source {macro.DB_ENV_PATH};
        expect <<EOF
        spawn  gsql -p {self.node_pri.db_port} -d {self.node_pri.db_name} \
        -c "copy {self.tb_name} from stdin;"
        expect ">>"
        send "2\\t3\\thh\\tstdin\\n"
        expect ">>"
        send "\\\\\.\\n"
        expect eof\n''' + '''EOF'''
        self.log.info(copy_cmd)
        copy_res = self.node_pri.sh(copy_cmd).result()
        self.log.info(copy_res)
        self.log.info('----验证数据是否输入成功----')
        res = self.pri_sh.execut_db_sql(
            f"select * from {self.tb_name};")
        self.log.info(res)
        self.assertIn('1 |   2 | ss         | dfd\n  '
                      '2 |   3 | hh         | stdin\n(2 rows)',
                      res, f'执行失败:{text}')

        text = '-----step3:执行copy to 标准输出stdout;expect:成功-----'
        self.log.info(text)
        copy_to_res = self.pri_sh.execut_db_sql(
            f"copy {self.tb_name} to stdout;")
        self.log.info(copy_to_res)
        self.assertIn('dfd', copy_to_res, f'执行失败:{text}')
        self.assertIn('stdin', copy_to_res, f'执行失败:{text}')

    def tearDown(self):
        text = '-----step4:清理环境;expect:成功-----'
        self.log.info(text)
        drop_res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.tb_name} cascade;")
        self.log.info(drop_res)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_res,
                      f'删表失败:{text}')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
